const { Controller } = require('egg')
const fs = require('fs')

class HomeController extends Controller {
//   async list() {
//     const { ctx } = this
//   }
  async sendComment() {
    const { url_md5, name, email, content } = this.ctx.request.body

    if (!url_md5) {
        this.ctx.body = {
            code: 500,
            msg: '缺少参数 url_md5',
            data: {}
        }
        return
    }
    if (!content) {
        this.ctx.body = {
            code: 500,
            msg: '缺少参数 content',
            data: {}
        }
        return
    }

    const lastCommentThisIp = await this.app.mysql.get('website_comment', {
        url_md5,
        ip: this.ctx.ip,
        is_del: 0
    }, {
        orders: [['create_time', 'desc']]
    })

    if (lastCommentThisIp && lastCommentThisIp.create_time && Date.parse(new Date()) - Number(lastCommentThisIp.create_time) < 180000) {
        this.ctx.body = {
            code: 500,
            msg: '3 分钟内只能评论一次',
            data: {}
        }
        return
    }


    const insert = await this.app.mysql.insert('website_comment', {
        url_md5,
        content,
        name: name || '',
        email: email || '',
        ip: this.ctx.ip,
        create_time: Date.parse(new Date())
    })

    this.ctx.body = {
        code: 200,
        msg: 'ok',
        data: { 
            insertId: insert.insertId
        }
    }
  }

  async getComments() {
    const { url_md5, page = 20 } = this.ctx.query
    const limit = 20

    if (!url_md5) {
        this.ctx.body = {
            code: 500,
            msg: '缺少参数 url_md5',
            data: {}
        }
        return
    }

    const listWhere = {
        url_md5,
        is_del: 0
    }
    const count = await this.app.mysql.count('website_comment', listWhere)
    const list = await this.app.mysql.select('website_comment', {
        where: listWhere,
        orders: [
            ['create_time', 'desc']
        ],
        limit,
        offset: limit * (page - 1)
    })

    this.ctx.body = {
        code: 200,
        msg: 'ok',
        data: {
            count,
            list: list.map(v => ({...v, content: v.content.toString(), name: v.name.toString()})),
            page: Number(page),
            limit
        }
    }
  }

  async nginxStatisticList() {
    this.ctx.body = {
        code: 200,
        msg: 'ok',
        data: this.ctx.helper.analysisNginxLog()
    }
  }

  async nginxStatisticDetail() {
    const filename = this.ctx.query.filename
    if (!filename) {
        this.ctx.body = {
            code: 500,
            msg: '缺少参数 filename',
            data: {}
        }
        return
    }

    const ifExist = fs.existsSync(`${this.app.config.nginxLogDir}${filename}`)
    if (!ifExist) {
        this.ctx.body = {
            code: 500,
            msg: '文件不存在',
            data: {}
        }
        return
    }
    this.ctx.body = {
        code: 200,
        msg: 'ok',
        data: this.ctx.helper.analysisNginxLogFile(filename)
    }
  }

  async gameRomLog() {
    const { data, mode } = this.ctx.query
    const d = JSON.parse(decodeURIComponent(atob(data)))
    
    await this.app.mysql.insert('website_gameroom_log', {
        type: mode,
        md5: d.md5,
        key: d.key,
        data: data,
        ip: this.ctx.state.clientIp,
        create_time: Date.parse(new Date())
    })
    console.log('mode', mode)

    switch (mode) {
        case 'check': {
            const js = `(function() {const data = JSON.parse(decodeURIComponent(atob('${data}')));document.getElementById('title').innerHTML = data.key.split('/').at(-1).replaceAll('.zip', '');document.getElementById('hash').innerHTML = data.hash;document.getElementById('download').addEventListener('click', function() { const a = document.createElement('a');a.href = \`/blog/gamerom/log?data=${data}&mode=download\`;a.click(); })})()`
            await this.ctx.render(`gamerom/gameRom.html`, { js })
        }; break
        case 'download': {
            const js = `<h2>Downloading</h2><script>(function() {const data = JSON.parse(decodeURIComponent(atob('${data}')));window.location.href=\`http://image-space.thebestxt.cc/\${data.key}\`})()</script>`
            this.ctx.body = await this.ctx.renderString('{{js|safe}}', { js })
        }; break
    }
  }
}

module.exports = HomeController
